import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Spin, Popover, Button, Affix, Table, message, Icon, Badge, Row, Col, Popconfirm } from 'antd';
import "styles/budget/budget-journal/budget-journal-detail-submit.scss"
import menuRoute from 'routes/menuRoute'
import budgetJournalService from 'containers/budget/budget-journal/budget-journal.service'
import Condition from 'components/condition'
const { If } = Condition;

class BudgetJournalDetailSubmit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      spinLoading: true,
      loading: true,
      data: [],
      headerAndListData: {},
      totalAmount: 0,
      headerData: {},
      pageSize: 10,
      page: 0,
      total: 0,
      pagination: {
        current: 0,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      organization: {},
      fileList: [],
      infoData: {},
      columns: [
        {          /*公司*/
          title: messages('budget.key85'/*公司*/), key: "companyName", dataIndex: 'companyName', width: '5%',
          render: companyName => (
            <Popover content={companyName}>
              {companyName}
            </Popover>)
        },
        {          /*部门*/
          title: messages('budget.key86'/*部门*/), key: "departmentName", dataIndex: 'departmentName', width: '5%',
          render: departmentName => (
            <Popover content={departmentName}>
              {departmentName}
            </Popover>)
        },
        {          /*员工*/
          title: messages('budget.key87'/*人员*/), key: "employeeName", dataIndex: 'employeeName', width: '5%',
          render: recode => (
            <Popover content={recode}>
              {recode}
            </Popover>)
        },
        {          /*预算项目*/
          title: messages('budget.key88'/*预算项目*/), key: "itemName", dataIndex: 'itemName', width: '10%',
          render: itemName => (
            <Popover content={itemName}>
              {itemName}
            </Popover>)
        },
        {          /*期间*/
          title: messages('budget.key89'/*期间*/), key: "periodName", dataIndex: 'periodName',
        },
        {          /*季度*/
          title: messages('budget.key90'/*预算季度*/), key: "periodQuarterName", dataIndex: 'periodQuarterName',
        },
        {          /*年度*/
          title: messages('budget.key91'/*预算年度*/), key: "periodYear", dataIndex: 'periodYear',
        },
        {          /*半年度*/
          title: messages('budget.key165')/*半年度*/, key: "periodSemiannualName", dataIndex: 'periodSemiannualName',
        },
        {          /*币种*/
          title: messages('budget.key92'/*币种*/), key: "currency", dataIndex: 'currency', width: 80,
        },
        {          /*汇率*/
          title: messages('budget.key93'/*汇率*/), key: "rate", dataIndex: 'rate', width: 80,
          render: rate => (
            <Popover content={rate}>
              {rate}
            </Popover>)
        },
        {          /*金额*/
          title: messages('budget.key94'/*金额*/), key: "amount", dataIndex: 'amount', width: 180,
          render: recode => (
            <Popover content={this.filterMoney(recode)}>
              {this.filterMoney(recode)}
            </Popover>)
        },
        {          /*本币今额*/
          title: messages('budget.key95'/*本币金额*/), key: "functionalAmount", dataIndex: 'functionalAmount', width: 180,
          render: recode => (
            <Popover content={this.filterMoney(recode)}>
              {this.filterMoney(recode)}
            </Popover>)
        },
        {          /*数字*/
          title: messages('budget.key96'/*数量*/), key: "quantity", dataIndex: 'quantity',
        },
        {          /*备注*/
          title: messages('budget.key97'/*行备注*/), key: "remark", dataIndex: 'remark',
          render: remark => (
            <Popover content={remark}>
              {remark}
            </Popover>)
        },
      ],
      budgetJournalPage: menuRoute.getRouteItem('budget-journal', 'key'),    //预算日记账

    };
  }

  componentWillMount = () => {
    this.getToleAmount();
    this.getBudgetJournalHead();
    this.getBudgetJournalLine();

  }

  //获取日记账总金额
  getToleAmount() {
    let infoDate = this.state.infoDate;
    budgetJournalService.getTotalCurrencyAmount(this.props.params.journalCode).then((response) => {
      let totalAmount = response.data;
      this.setState({ infoDate, totalAmount });
    })
  }


  //根据attachmentOID，查询附件
  getFileByAttachmentOID = oids => {
    let services = oids.map(oid => budgetJournalService.getFileByAttachmentOID({ oid }));
    Promise.all(services).then(res => {
      const { fileList } = this.state;
      res.map(resItem => {
        fileList.addIfNotExist(resItem.data);
      });
      this.setState({ fileList })
    }).catch(e => {
      message.error(`${messages('budget.key98'/*获取附件失败*/)},${e.response.data.message}`);
    });
  }

  //获取日记账头
  getBudgetJournalHead() {
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalHeaderDetil(budgetCode).then((request) => {
      this.getDimensionByStructureId(request.data.structureId);
      let headerData = request.data;
      headerData.attachmentOID && this.getFileByAttachmentOID(headerData.attachmentOID);
      let headerAndListData = {
        dto: request.data,
        list: [],
      }
      this.setState({
        headerData: headerData,
        headerAndListData: headerAndListData,
        infoData: headerData,
      }, () => {
        this.getToleAmount();
      })
    })
  }

  //获取日记账行
  getBudgetJournalLine() {
    let params = {};
    params.page = this.state.page;
    params.size = this.state.pageSize;
    this.setState({
      loading: true,
    })
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalLineDetil(budgetCode, params).then((response) => {
      this.setState({
        loading: false,
      })
      let listData = response.data;
      this.setState({
        data: listData,
        total: Number(response.headers['x-total-count']),
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch((e) => {
      this.setState({
        loading: false,
      })
      message.error(e.response.data.message);
    })

  }

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getBudgetJournalLine();
      })
  };




  //根据预算表id，获得维度
  getDimensionByStructureId = (value) => {
    let params = {};
    params.isEnabled = true;
    params.structureId = value;
    budgetJournalService.getDimensionByStructureId(params).then((resp) => {
      this.getColumnsAndDimensionhandleData(resp.data);

    })
  }

  //根据预算表的维度.获取维度Columuns
  getColumnsAndDimensionhandleData(dimensionList) {
    let columns = this.state.columns;
    for (let i = 0; i < dimensionList.length; i++) {
      const item = dimensionList[i];
      const priority = item.sequenceNumber;
      columns.push(
        {
          title: `${item.dimensionName}`, key: `dimension${priority}ValueName`, dataIndex: `dimension${priority}ValueName`,
          render: recode => (
            <Popover content={recode}>
              {recode}
            </Popover>)
        }
      )
    }
    this.setState({
      columns,
    }, () => {
      this.setState({
        spinLoading: false
      })
    })
  }

  //返回状态
  getStatus = () => {
    const infoData = this.state.infoData;
    switch (infoData.status) {
      case 'NEW': { return <Badge status="processing" text={infoData.statusName} /> }
      case 'SUBMIT': { return <Badge status="warning" text={infoData.statusName} /> }
      case 'SUBMIT_RETURN': { return <Badge status="warning" text={infoData.statusName} /> }
      case 'REJECT': { return <Badge status="error" text={infoData.statusName} /> }
      case 'CHECKED': { return < Badge status="default" text={infoData.statusName} /> }
      case 'CHECKING': { return <Badge status="default" text={infoData.statusName} /> }
      case 'POSTED': { return <Badge status="default" text={infoData.statusName} /> }
      case 'BACKLASH_SUBMIT': { return <Badge status="default" text={infoData.statusName} /> }
      case 'BACKLASH_CHECKED': { return <Badge status="default" text={infoData.statusName} /> }
      default: { return <Badge status="default" text={infoData.statusName} /> }
    }
  }



  //获取附件
  getFile = () => {
    const fileList = this.state.fileList;
    let file_arr = [];
    fileList.map((link) => {
      file_arr.push(<div key={link.fileURL}><a href={link.fileURL} target="_blank"><Icon type="paper-clip" /> {link.fileName}</a> </div>)
    })
    return file_arr.length > 0 ? file_arr : '-';

  }

  //撤回
  handleRevocation = () => {
    let header = this.state.headerData;
    if (header.formOid) {
      //工作流
      message.warning("工作流撤回");
      this.setState({ spinLoading: true })
      const dataValue = {
        "entities": [
          {
            "entityOID": this.state.headerAndListData.dto.documentOid,
            "entityType": this.state.headerAndListData.dto.documentType
          }]
      }
      budgetJournalService.revocationJournalWorkflow(dataValue).then((item) => {
        this.context.router.push(this.state.budgetJournalPage.url);
      }).catch((e) => { })
    } else {
      //非工作流
      message.warning("复核撤回");
      const headerIds = [];
      headerIds.push(this.state.headerData.id);
      budgetJournalService.revocationJournal(this.props.user.id, headerIds).then((item) => {
        this.context.router.push(this.state.budgetJournalPage.url);
      }).catch((e) => { })
    }
  }

  //返回预算日记账查询
  handleReturn = () => {
    let path = this.state.budgetJournalPage.url;
    this.context.router.push(path);
  };

  render() {
    const { data, columns, infoData, pagination, spinLoading } = this.state;
    return (
      <div className="budget-journal-detail-submit">
        <div className="base-info">
          <div className="base-info-header">
            {messages('budget.key100'/*基本信息*/)}
          </div>

          <Row className="base-info-cent" type="flex" gutter={10}>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key101'/*状态*/)}:</div>
              <div className="beep-info-text">
                {this.getStatus()}
              </div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key102'/*预算日记账编号*/)}:</div>
              <div className="beep-info-text">{infoData.journalCode ? infoData.journalCode : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key94'/*金额*/)}:</div>
              <div className="beep-info-text">
                {this.state.totalAmount}
              </div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key103'/*申请人*/)}:</div>
              <div className="beep-info-text">{infoData.employeeName ? infoData.employeeName : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key86'/*部门*/)}:</div>
              <div className="beep-info-text">{infoData.unitName ? infoData.unitName : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('common.remark')/*备注*/}:</div>
              <div className="beep-info-text">{infoData.description ? infoData.description : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key104'/*创建时间*/)}:</div>
              <div className="beep-info-text">{String(infoData.createdDate).substring(0, 10)}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key105'/*预算日记账类型*/)}:</div>
              <div className="beep-info-text">{infoData.journalTypeName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key106'/*预算表*/)}:</div>
              <div className="beep-info-text">{infoData.structureName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key107'/*场景*/)}:</div>
              <div className="beep-info-text">{infoData.scenario}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key108'/*版本*/)}:</div>
              <div className="beep-info-text">{infoData.versionName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key109'/*编制期段*/)}:</div>
              <div className="beep-info-text">{infoData.periodStrategyName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key110'/*附件*/)}:</div>
              <div className="beep-info-text">{this.getFile()}</div>
            </Col>

          </Row>
        </div>
        <Spin spinning={spinLoading}>
          <Table columns={columns}
                 dataSource={data}
                 bordered
                 size="middle"
                 scroll={{ x: '150%' }}
                 rowKey="id"
                 pagination={pagination}
          />
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          <If value={infoData.status === "SUBMIT"}>
            <Popconfirm placement="topLeft"
                        title={messages('budget.key163')/*确定撤回吗*/}
                        onConfirm={this.handleRevocation}>
              <Button className="button-callback">{messages('budget.key99'/*撤回*/)}</Button>
            </Popconfirm>
          </If>
          <Button onClick={this.handleReturn}>{messages('budget.key111'/*返回*/)}</Button>
        </Affix>
      </div>

    )
  }

}


BudgetJournalDetailSubmit.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    organization: state.login.organization
  }
}

export default connect(mapStateToProps)(BudgetJournalDetailSubmit);
